package com.study.controller;

import com.study.dao.Data;
import com.study.entity.AppCategory;
import com.study.entity.AppInfo;
import com.study.entity.DataDictionary;
import com.study.entity.PageInfo;
import com.study.service.IAppCategoryService;
import com.study.service.IAppInfoService;
import com.study.service.IDataDictionaryService;
import com.study.utils.UUIDUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("app")
public class AppInfoController {
    @Autowired
    private IAppInfoService appInfoService;
    @Autowired
    private IAppCategoryService appCategoryService;
    @Autowired
    private IDataDictionaryService dataDictionaryService;

    @RequestMapping("list")
    public String list(Model model,  AppInfo appInfo,
                       @RequestParam(value = "page", required = false, defaultValue = "1") Integer page,
                       @RequestParam(value = "size", required = false, defaultValue = "2") Integer size) {

        if(appInfo.getAppName()==""){appInfo.setAppName(null);}
        List<AppInfo> list = appInfoService.findList(appInfo, page, size);
        int total = appInfoService.findList(appInfo).size();
        PageInfo<AppInfo> pageInfo =new PageInfo<>(page,size,total,list);
        model.addAttribute("pageInfo", pageInfo);
        model.addAttribute("appInfo", appInfo);
        return "app/list";
    }

    @RequestMapping("getLevel2")
    @ResponseBody
    public List<AppCategory> getLevel2(Integer parentId) {
        return appCategoryService.findListByPid(parentId);
    }

    @RequestMapping("add")//约定大于配置原则
    public void add() {
    }//页面跳转


    @RequestMapping("doAdd")
    public String doAdd(Model model, @Valid AppInfo appInfo, BindingResult bindingResult,
                        @RequestParam(name = "img", required = false) MultipartFile multipartFile) throws IOException {
        if(bindingResult.hasErrors()){
            List<FieldError> fieldErrors = bindingResult.getFieldErrors();
            Map<String ,String> err=new HashMap<>();
            for(FieldError error:fieldErrors){
                err.put(error.getField(),error.getDefaultMessage());
            }
            model.addAttribute("appInfo", appInfo);
            model.addAttribute("errors",err);
            return "redirect:app/add";
        }
        int i=1;
        if(!multipartFile.isEmpty()) {
            //TODO 判断文件的属性
            String filePath = UUIDUtils.uuid() + multipartFile.getOriginalFilename();//获取文件名
            multipartFile.transferTo(new File("C:\\Users\\zhuhaier\\Pictures\\temp", filePath));//保存文件

            appInfo.setImgUrl(filePath);//设置文件路径
            appInfo.setSize((double) multipartFile.getSize());//设置文件大小

            i = appInfoService.saveOne(appInfo);//保存文件
        }
        if (i != 0) {
            return "redirect:list";//重定向到app列表页面
        } else {
            model.addAttribute("appInfo", appInfo);//用于数据回写
            return "/app/add";//转发到添加页面
        }
    }

    @RequestMapping("dataDictionary")
    @ResponseBody
    public List<DataDictionary> dataDictionary(DataDictionary dataDictionary) {
        return dataDictionaryService.findList(dataDictionary);
    }

    @RequestMapping("update")
    public String update(Model model,Integer appId){
        AppInfo appInfo = appInfoService.findOneById(appId);
        model.addAttribute("appInfo",appInfo);
        return "app/update";
    }
    @RequestMapping("doUpdate")
    public String doUpdate(Model model,@Valid AppInfo appInfo, BindingResult bindingResult,
                  @RequestParam(name = "img", required = false) MultipartFile multipartFile) throws IOException {
        if(bindingResult.hasErrors()){//判断数据格式，如有错则将错误回写给Jsp
            List<FieldError> fieldErrors = bindingResult.getFieldErrors();
            Map<String ,String> err=new HashMap<>();
            for(FieldError error:fieldErrors){
                err.put(error.getField(),error.getDefaultMessage());
            }
            model.addAttribute("appInfo", appInfo);
            model.addAttribute("errors",err);
            return "/app/update";
        }
        if(!multipartFile.isEmpty()) {
            String filePath = UUIDUtils.uuid() + multipartFile.getOriginalFilename();//获取文件名
            multipartFile.transferTo(new File("C:\\Users\\Administrator.win7-PC\\IdeaProjects\\appmng2\\src\\main\\webapp\\statics\\images", filePath));//保存文件
            appInfo.setImgUrl(filePath);//设置文件路径
            appInfo.setSize((double) multipartFile.getSize());//设置文件大小
        }
        appInfo.setModifyTime(new Date());
        int i = appInfoService.updateOne(appInfo);
        if(i!=0){
            return "redirect:list";//重定向到app列表页面
        }else {
            model.addAttribute("appInfo", appInfo);//用于数据回写
            return "/app/update";//转发到添加页面
        }
    }
    @RequestMapping("shelf")
    @ResponseBody
    public Data hitShelves(Integer appId,String todo){
        Data data=new Data();
        switch (todo){
            case "open":
                appInfoService.hitShelves(appId);
                data.setErrorCode(0);
                data.setResultMsg("success");
                break;
            case "close":
                appInfoService.offShelves(appId);
                data.setErrorCode(0);
                data.setResultMsg("success");
                break;
        }

        return data;
    }
}
